package com.crazymaker.springcloud.base.filter;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.common.context.SessionHolder;
import com.crazymaker.springcloud.standard.redis.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class SessionIdFilter extends OncePerRequestFilter {

    private RedisRepository redisRepository;

    private RedisOperationsSessionRepository sessionRepository;

    public SessionIdFilter(RedisRepository redisRepository, RedisOperationsSessionRepository sessionRepository) {
        this.redisRepository = redisRepository;
        this.sessionRepository = sessionRepository;
    }

    /**
     * 是否应该过滤
     * @param request
     * @return
     * @throws ServletException
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String userId = request.getHeader(SessionConstants.USER_IDENTIFIER);
        if (StringUtils.isNotBlank(userId)) {
            return false;
        }
        return true;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 通过UID找到SID，并往下传递
        String userId = request.getHeader(SessionConstants.USER_IDENTIFIER);
        SessionHolder.setUserIdentifer(userId);

        String sessionId = redisRepository.getSessionId(userId);
        if (StringUtils.isNotBlank(sessionId)) {
            Session session = sessionRepository.findById(sessionId);
            if (session != null) {
                SessionHolder.setSid(sessionId);
            }
        }
        filterChain.doFilter(request, response);
    }
}
